# Author: HZT
# Date: 2023/8/24
from selenium.common import NoSuchElementException, TimeoutException
from config.config_loader import config
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class Base:
    def __init__(self, driver):
        self.driver = driver

    # 显示等待
    def base_find(self, location):
        print("======>正在查找:{}".format(location))
        try:
            return WebDriverWait(self.driver, config.TIME_OUT, config.POLL).until(
                EC.presence_of_element_located(location))
        except TimeoutException:
            print(f"元素{location[0]} - {location[1]}未找到")
            raise

    def base_finds(self, location):
        print("======>正在查找:{}".format(location))
        try:
            return WebDriverWait(self.driver, config.TIME_OUT, config.POLL).until(
                EC.presence_of_all_elements_located(location))
        except TimeoutException:
            print(f"元素{location[0]} - {location[1]}未找到")
            raise

    def base_find_first(self, location):
        print("======>正在查找:{}".format(location))
        elements = WebDriverWait(self.driver, config.TIME_OUT, config.POLL).until(
            EC.presence_of_all_elements_located(location))
        if elements:
            return elements[0]
        else:
            raise NoSuchElementException("未找到匹配的元素")

    # 输入
    def base_input(self, location, text):
        # 获取元素
        el = self.base_find(location)
        # 清空
        el.clear()
        # 输入
        el.send_keys(text)

    # 点击
    def base_click(self, location):
        print("======>正在查找:{}".format(location))
        try:
            WebDriverWait(self.driver, config.TIME_OUT, config.POLL).until(EC.element_to_be_clickable(location)).click()
        except TimeoutException:
            print(f"元素{location[0]} - {location[1]}未找到")
            raise

    # 获取文本
    def base_get_first_text(self, location):
        return self.base_find_first(location).text

    # 获取文本
    def base_get_text(self, location):
        return self.base_find(location).text

    # 截图
    def base_get_img(self):
        img_path = config.DIR_PATH + "/img/log/{}.png".format(time.strftime("%Y-%m-%d %H-%M-%S"))
        self.driver.get_screenshot_as_file(img_path)

    # 切换frame
    def base_switch_frame(self, location):
        el = self.base_find(location)
        self.driver.switch_to.frame(el)

    # 恢复frame
    def base_default_frame(self):
        self.driver.switch_to.default_content()

    # 句柄
    def base_switch_window(self, target):
        # 获取当前窗口句柄
        current_window_handle = self.driver.current_window_handle

        # 如果传入的参数是字符串（标题），则按标题切换窗口
        if isinstance(target, str):
            for handle in self.driver.window_handles:
                self.driver.switch_to.window(handle)
                # 获取当前窗口标题并与目标标题比较
                if self.driver.title == target:
                    print(f"已找到窗口 '{target}' 并切换")
                    return f"已找到窗口 '{target}' 并切换"

        # 如果传入的参数是整数（索引），则按索引切换窗口
        elif isinstance(target, int):
            if 0 <= target < len(self.driver.window_handles):
                self.driver.switch_to.window(self.driver.window_handles[target])
                print(f"已切换到窗口索引 {target}")
                return f"已切换到窗口索引 {target}"
            else:
                print(f"窗口索引 {target} 无效")

        # 如果未找到目标窗口，则切换回原窗口
        self.driver.switch_to.window(current_window_handle)
        print("未找到目标窗口，已切换回原窗口")
        return "未找到目标窗口，已切换回原窗口"
